package com.luboyan.CBillbill.service.file.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luboyan.CBillbill.exception.ConditionException;
import com.luboyan.CBillbill.mapper.file.DanmuMapper;
import com.luboyan.CBillbill.dao.file.Danmu;
import com.luboyan.CBillbill.dao.file.Video;
import com.luboyan.CBillbill.service.file.DanmuService;
import com.luboyan.CBillbill.service.file.VideoService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 弹幕业务逻辑实现
 */
@Service
public class DanmuServiceImpl implements DanmuService {

    @Autowired
    private DanmuMapper danmuMapper;

    @Autowired
    private VideoService videoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取弹幕
     * 优先获取redis中的数据
     */
    @Override
    public List<Danmu> getDanmus(Long videoId, String startTime, String endTime) throws Exception{
        if (videoId == null) {
            throw new ConditionException("非法参数！");
        }
        Video video = videoService.getVideoById(videoId);
        if (video == null) {
            throw new ConditionException("非法视频！");
        }

        String key = "dm-video-" + videoId;
        String value = redisTemplate.opsForValue().get(key);
        List<Danmu> list;
        if (!StringUtils.isNullOrEmpty(value)) {
            list = JSONArray.parseArray(value, Danmu.class);
            //判断时间
            if(!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date startDate = sdf.parse(startTime);
                Date endDate = sdf.parse(endTime);
                List<Danmu> childList = new ArrayList<>();
                for(Danmu danmu:list){
                    Date createTime = danmu.getCreateTime();
                    if(createTime.after(startDate) && createTime.before(endDate)){
                        childList.add(danmu);
                    }
                }
                list = childList;
            }
        } else {
            JSONObject params = new JSONObject();
            params.put("videoId", videoId);
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            list = danmuMapper.getDanmus(params);
            //将数据库中的弹幕也写入redis中
            redisTemplate.opsForValue().set(key, JSONObject.toJSONString(list));
        }

        return list;
    }

    /**
     * 将弹幕存入redis
     */
    @Override
    public void addDanmusToRedis(Danmu danmu) {
        String key = "danmu-video-" + danmu.getVideoId();
        String value = redisTemplate.opsForValue().get(key);
        List<Danmu> list = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(value)) {
            list = JSONArray.parseArray(value, Danmu.class);
        }
        list.add(danmu);
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(list));
    }

    /**
     * 将弹幕存入数据库
     */
    @Override
    public void addDanmu(Danmu danmu) {
        Long videoId = danmu.getVideoId();
        if (videoId == null) {
            throw new ConditionException("非法参数！");
        }
        Video video = videoService.getVideoById(videoId);
        if (video == null) {
            throw new ConditionException("非法视频！");
        }
        danmuMapper.insert(danmu);
    }

    /**
     * 将弹幕存入数据库（异步）
     */
    @Override
    @Async
    public void asyncAddDanmu(Danmu danmu) {
        Long videoId = danmu.getVideoId();
        if (videoId == null) {
            throw new ConditionException("非法参数！");
        }
        Video video = videoService.getVideoById(videoId);
        if (video == null) {
            throw new ConditionException("非法视频！");
        }
        danmuMapper.insert(danmu);
    }
}
